import subprocess
import sys
import os
libs =[
    'asgiref',
    'Django',
    'djangorestframework',
    'djangorestframework_simplejwt',
    'django-cors-headers',
    'django-redis',
    'mysqlclient',
    'channels',
    'channels_redis',
    'daphne',
    'redis',
]
def run_in_new_cmd(command):
    return subprocess.Popen(['start', 'cmd', '/K', command], shell=True)

def check_libs():
    raw_piplist = subprocess.run(['pip','list'], shell=True, capture_output=True, text=True)
    lines = raw_piplist.stdout.splitlines()[2:]
    local_libs = [line.split()[0] for line in lines]

    wait4libs =[]
    for lib in libs:
        if lib not in local_libs:
            wait4libs.append(lib)

    if wait4libs:
        print("以下库未安装：")
        for lib in wait4libs:
            print(lib)
        
        myinput = input("是否执行安装(y/n)：")
        if myinput.lower() == 'y':
            install_libs(wait4libs)
        else:
            exit()
    
    boot_project()

def install_libs(wait4libs):
    for lib in wait4libs:
        subprocess.run(['pip','install',lib], shell=True)
    check_libs()

def boot_project():
    current_file_path = os.path.realpath(__file__)
    root_directory = os.path.dirname(current_file_path)
    print("项目根目录：", root_directory)
    try:
        django_command = 'python sysu-back/manage.py runserver'
        run_in_new_cmd(django_command)
    except Exception as e:
        print("Django启动失败，错误信息：", e)

    try:
        redis_bat_path = os.path.join(root_directory, 'Redis', 'start.bat')
        run_in_new_cmd(redis_bat_path)
    except Exception as e:
        print("Redis启动失败，错误信息：", e)

    try:
        vue_command = 'cd sysu-front/my-vue-project && npm run dev'
        run_in_new_cmd(vue_command)
    except Exception as e:
        print("Vue启动失败，错误信息：", e)
        
    sys.exit()
check_libs()